﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CRM.Entity;
using CRM.BLL;
using System.Text;
using DP.Common;
using DP.Web.UI;
using System.Data;

namespace CRM.Web.CallBackManage
{
    public partial class Assignment : Common.PageBase
    {
        T_USER_BLL userBll = new T_USER_BLL();
        private T_DEPARTMENT_BLL departmentBll = new T_DEPARTMENT_BLL();
        T_BUSINESSDIVISION_BLL businessDivisionBll = new T_BUSINESSDIVISION_BLL();
        T_CALLBACK_PLAN_BLL callBackPlanBll = new T_CALLBACK_PLAN_BLL();
        T_CALLBACK_TASK_BLL callBackTaskBll = new T_CALLBACK_TASK_BLL();


        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            PageHelper.SetPrePageUrl(this.Page);
            if (PageHelper.GetQueryString(this.Page, "PageTarget") != "Opener")
            {
                PageHelper.SetGoBackUrl(this.Page, btnCancel, StaticConstant.NotBackUrl);
                btnCancel.Attributes["onclick"] = UserLoginInfo.FilterBackUrl(btnCancel.Attributes["onclick"]);
            }
            else
            {
                PageHelper.SetClose(this.Page, btnCancel);
                btnCancel.Value = "关 闭";
            }
        }


        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                ddlBusinessDivisionBinding();
                ddlDepartmentBinding();
                gvDataBindingUser();

                ddlCallBackPlanBinding();


                pageInit();
            }
        }




        private void pageInit()
        {
            lblCount.Text = callBackTaskBll.GetCount(GetConditions().ToString()).ToString();        
        }


        /// <summary>
        /// 页面数据绑定
        /// </summary>
        private void gvDataBindingUser()
        {
            #region 查询条件字符串
            StringBuilder sql = GenerationSQLStringUser();
            #endregion

            List<T_USER_Entity> list;

            //获取总的记录条数
            gvList.RecordCount = (int)userBll.GetCount(sql.ToString());

            list = userBll.GetList(sql.ToString(), gvList.SortConditions);

            gvList.DataSource = list;
            gvList.DataKeyNames = new string[] { "USERID", "UserName", "LoginName" };
            gvList.DataBind();

        }

        /// <summary>
        /// DDLs the business division binding.
        /// </summary>
        private void ddlBusinessDivisionBinding()
        {
            ddlBusinessDivision.DataSource = businessDivisionBll.GetCacheList(this.Page, String.Format(" and Status = {0} ", ((int)Status.启用).ToString()), "Status");
            ddlBusinessDivision.DataTextField = "BUSINESSDIVISIONNAME";
            ddlBusinessDivision.DataValueField = "BUSINESSDIVISIONCODE";
            ddlBusinessDivision.DataBind();
            if (!UserLoginInfo.IsAdministrator())
            {
                ddlBusinessDivision.SelectedValue = _userLoginInfo.UserEntity.BUSINESSDIVISIONCODE.ToString();
                ddlBusinessDivision.Enabled = false;
            }

        }

        /// <summary>
        /// DDLs the department binding.
        /// </summary>
        private void ddlDepartmentBinding()
        {

            StringBuilder sql = new StringBuilder();
            sql.Append(String.Format(" and BUSINESSDIVISIONCODE = '{0}' ", ddlBusinessDivision.SelectedValue.Trim()));
            sql.Append(String.Format(" and ISCENTER = '{0}' ", ((int)DepartmentType.呼叫中心).ToString()));
            sql.Append(" and DepartmentID in (select DepartmentID from T_User ) ");

            ddlDepartment.DataSource = departmentBll.GetList(sql.ToString());
            ddlDepartment.DataTextField = "DEPARTMENTNAME";
            ddlDepartment.DataValueField = "DEPARTMENTID";
            ddlDepartment.DataBind();
            if (!UserLoginInfo.IsAdministrator())
            {
                ddlDepartment.Enabled = false;
                ddlDepartment.SelectedValue = _userLoginInfo.UserEntity.DEPARTMENTID.ToString();
            }
            
            
        }

        private void ddlCallBackPlanBinding()
        {
            StringBuilder sql = new StringBuilder();
            ddlCallBackPlan.DataSource = callBackPlanBll.GetList(sql.ToString());
            ddlCallBackPlan.DataTextField = "TASK_NAME";
            ddlCallBackPlan.DataValueField = "TASK_ID";
            ddlCallBackPlan.DataBind();
        }


        /// <summary>
        /// 生成查询条件字符串
        /// </summary>
        private StringBuilder GenerationSQLStringUser()
        {
            StringBuilder sql = new StringBuilder();
            sql.Append(" and (ISSYSTEMADMIN <> '1' or ISSYSTEMADMIN is null) ");
            sql.Append(String.Format(" and DEPARTMENTID = '{0}' ", ddlDepartment.SelectedValue));
            sql.Append(String.Format(" and BUSINESSDIVISIONCODE = '{0}' ", ddlBusinessDivision.SelectedValue.Trim()));
            
            return sql;

        }


       
        protected void btnSearch_Click(object sender, EventArgs e)
        {

        }


        /// <summary>
        /// Handles the Click event of the btnAssign control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void btnAssign_Click(object sender, EventArgs e)
        {
            string Sets = "";
            string setsTemplate = " ASSIGN_DATE = sysdate, CURRENT_ID = '{0}', CURRENT_NAME = '{1}', CASE_ASSIN_STATUS = '{2}', LASTMODIFYPEOPLEID = '{3}', LASTMODIFYPEOPLE = '{4}', LASTMODIFYTIME = sysdate ";


            List<T_USER_Entity> userList = GetSelected(gvList);
            if (userList.Count == 0)
            {
                PageHelper.ShowMessage(this.Page, "请选择分配的目标人！");
                return;
            }

            

            int userCount = userList.Count;
            int assignCount = StringHelper.ToInt(txtAssignmentNumber.Text.Trim());
            int Count = StringHelper.ToInt(lblCount.Text.Trim());
            if (assignCount == 0)
            {
                assignCount = IntHelper.divideMax(Count, userList.Count);
            }
            else if(Count < userList.Count*assignCount)
            {
                PageHelper.ShowMessage(this.Page, "待分配名单不足！");
                return;
            }


            try
            {
                //for (int i = 0; i < callLossCount; i++)
                //{
                //    //user = userList[i % userCount];
                //    //Sets = String.Format(setsTemplate, user.USERID, user.USERNAME, _userLoginInfo.UserEntity.USERID, _userLoginInfo.UserEntity.USERNAME,
                //    //   _userLoginInfo.UserEntity.BUSINESSDIVISIONID, _userLoginInfo.UserEntity.BUSINESSDIVISIONNAME, _userLoginInfo.UserEntity.BUSINESSDIVISIONCODE, lostAssignmentLimited);
                //    //callLossBll.Update(Sets, String.Format(" and ID = '{0}' ", callLossIdList[i].ToString()), 1);
                //}
                foreach (var user in userList)
                {
                    Sets = String.Format(setsTemplate, user.USERID, user.USERNAME, (int)CallBackTaskAssignStatus.已分配, _userLoginInfo.UserEntity.USERID, _userLoginInfo.UserEntity.USERNAME);
                    callBackTaskBll.Update(Sets, GetConditions().ToString(), assignCount);
                }
                pageInit();
                PageHelper.ShowMessage(this.Page, "分配成功！");
            }
            catch (Exception ex)
            {
                PageHelper.ShowMessage(this.Page, "分配失败！");
            }


        }

        public string GetConditions()
        {
            StringBuilder sql = new StringBuilder();
            sql.Append(String.Format(" and CASE_ASSIN_STATUS = '{0}' ", "0"));
            sql.Append(String.Format(" and TASK_ID = '{0}' ", ddlCallBackPlan.SelectedValue.Trim()));
            sql.Append(String.Format(" and BUSINESSDIVISIONCODE = '{0}' ", ddlBusinessDivision.SelectedValue.Trim()));
            return sql.ToString();

        }

        protected void ddlDepartment_SelectedIndexChanged(object sender, EventArgs e)
        {
            gvDataBindingUser();
        }

        protected void ddlBusinessDivision_SelectedIndexChanged(object sender, EventArgs e)
        {
            ddlDepartmentBinding();
            gvDataBindingUser();
            ddlCallBackPlanBinding();
            pageInit();
        }

        protected void ddlCallBackPlan_SelectedIndexChanged(object sender, EventArgs e)
        {
            lblCount.Text = callBackTaskBll.GetCount(GetConditions().ToString()).ToString();            
        }

        private List<T_USER_Entity> GetSelected(GridView gv)
        {
            List<T_USER_Entity> list = new List<T_USER_Entity>();
            if (gv == null) return list;
            T_USER_Entity entity;
            CheckBox cb;
            foreach (GridViewRow gvr in gv.Rows)
            {
                cb = gvr.FindControl("cbItem") as CheckBox;
                if (cb == null) continue;
                if (!cb.Checked) continue;
                entity = new T_USER_Entity();
                entity.USERID = StringHelper.ToInt(gv.DataKeys[gvr.RowIndex].Values["USERID"].ToString(), 0);
                entity.USERNAME = gv.DataKeys[gvr.RowIndex].Values["UserName"].ToString();
                entity.LOGINNAME = gv.DataKeys[gvr.RowIndex].Values["LoginName"].ToString();
                list.Add(entity);
            }
            return list;
        }



















    }
}
